package com.sloth.config;

import com.sloth.pojo.Customer;
import com.sloth.service.CustomerService;
import com.sloth.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CustomerArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private CustomerService customerService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> clazz = parameter.getParameterType();
        return clazz == Customer.class;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
        HttpServletResponse response = webRequest.getNativeRequest(HttpServletResponse.class);


        String ticket = "";
        //得到所有的cookies
        Cookie[] cookies = request.getCookies();

        //循环cookies得到每个具体的cookie值
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("customerTicket")) {
                ticket = cookie.getValue();
            }
        }

        if (ticket == null) {
            return null;
        }

        return customerService.getCustomerByCookie(ticket,request,response);
    }
}
